package com.boe.csb.core.common.utils;

import com.boe.csb.core.common.BoeEmailContentConfig;
import com.boe.csb.core.common.status.CertificationStatus;
import com.google.common.collect.Maps;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.PostConstruct;
import java.util.Map;

@Component
@Scope("singleton")
public class MailTemplate {
	

	public static String RELEASE = "release";
	public static String SUBSCRIBE = "subscribe";
	
    public enum ETplType {
        ACTIVE,//激活邮件
        FORGET_PASSWORD,//忘记密码邮件
        SERVICE_AUDIT,//服务校审
        APPROVAL,//审批通知
        CERTIFICATION;//用户校审
    }

    private static final Logger logger = LoggerFactory.getLogger(MailTemplate.class);

    @Autowired
    private FreeMarkerConfigurer freemarkerConfig;

    private static Map<ETplType, Template> tplMap = Maps.newHashMap();

    @PostConstruct
    public void init() {//FIXME 之后又新类型的邮件模板请新添加init的方法,并在初始化的时候调用
        initActiveMail();
    }

    private void initActiveMail() {
        try {
            String activeMail = PropertyUtils.getProperty("mail.tpl.active");
            Template activeMailTpl = freemarkerConfig.getConfiguration().getTemplate(activeMail);
            tplMap.put(ETplType.ACTIVE, activeMailTpl);

            String forgetPasswordMail = PropertyUtils.getProperty("mail.tpl.forgetPassword");
            Template forgetPasswordMailTpl = freemarkerConfig.getConfiguration().getTemplate(forgetPasswordMail);
            tplMap.put(ETplType.FORGET_PASSWORD, forgetPasswordMailTpl);

            String serviceAuditMail = PropertyUtils.getProperty("mail.tpl.serviceAudit");
            Template serviceAuditMailTpl = freemarkerConfig.getConfiguration().getTemplate(serviceAuditMail);
            tplMap.put(ETplType.SERVICE_AUDIT, serviceAuditMailTpl);

            String certificationMail = PropertyUtils.getProperty("ail.tpl.certification");
            Template certificationMailTpl = freemarkerConfig.getConfiguration().getTemplate(certificationMail);
            tplMap.put(ETplType.CERTIFICATION, certificationMailTpl);
            
            String approval = PropertyUtils.getProperty("mail.tpl.approval");
            Template approvalMailTpl = freemarkerConfig.getConfiguration().getTemplate(approval);
            tplMap.put(ETplType.APPROVAL, approvalMailTpl);
            
        } catch (Exception e) {
            logger.error("", e);
        }
    }

	/**
	 * 生成注册激活邮件模板
	 * @param params
	 * @param type
	 * @return
	 */
	public static String generateActiveMail(String activeURL){

		String html = "";

		try{
			Template tpl = tplMap.get(ETplType.ACTIVE);
			if(tpl == null){
				logger.error("contenxt don't init email template of type {}.", ETplType.ACTIVE);
				return activeURL;
			}

			Map<String, String> param = Maps.newHashMap();
			param.put("activeURL", activeURL);
	        html = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, param);
		}catch(Exception e){
			logger.error("", e);
			html = activeURL;
		}
		return html;
	}


	/**
	 * 生成忘记密码邮件模板
	 */
	public static String generateForgetPasswordMail(String newPassword) {
		String html = "";

		try {
			Template tpl = tplMap.get(ETplType.FORGET_PASSWORD);
			if (tpl == null) {
				logger.error("contenxt don't init email template of type {}.", ETplType.FORGET_PASSWORD);
				return newPassword;
			}

            Map<String, String> param = Maps.newHashMap();
            param.put("newPassword", newPassword);
            html = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, param);
        } catch (Exception e) {
            logger.error("生成忘记密码邮件模板失败", e);
            html = newPassword;
        }
        return html;
    }

    /**
     * 生成用户校审反馈
     */
    public static String generateCertificationMail(CertificationStatus status, String comment) {
        String emailContent = CertificationStatus.ALLOW == status ? BoeEmailContentConfig.ALLOW_CONTENT : BoeEmailContentConfig.REJECT_CONTENT;

        String html = "";
        try {
            Template tpl = tplMap.get(ETplType.CERTIFICATION);
            if (tpl == null) {
                logger.error("contenxt don't init email template of type {}.", ETplType.CERTIFICATION);
                return emailContent;
            }

            Map<String, String> param = Maps.newHashMap();
            param.put("emailContent", emailContent);
            param.put("comment", comment);
            html = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, param);
        } catch (Exception e) {
            logger.error("生成用户校审反馈失败", e);
            html = emailContent;
        }
        return html;
    }

    /**
     * 生成服务校审反馈
     */
    public static String generateServiceAuditMail(boolean approveFlag, String boeApiName, String publishOrSubscribe) {
        String emailContent = approveFlag ? BoeEmailContentConfig.ACTIVE_CONTENT : BoeEmailContentConfig.FORBIDDEN_CONTENT;
        emailContent = emailContent.replace("${apiName}", boeApiName).replace("${publishOrSubscribe}", publishOrSubscribe);

        String html = "";
        try {
            Template tpl = tplMap.get(ETplType.SERVICE_AUDIT);
            if (tpl == null) {
                logger.error("contenxt don't init email template of type {}.", ETplType.SERVICE_AUDIT);
                return emailContent;
            }

            Map<String, String> param = Maps.newHashMap();
            param.put("emailContent", emailContent);
            html = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, param);
        } catch (Exception e) {
            logger.error("生成服务校审反馈失败", e);
            html = emailContent;
        }
        return html;
    }
    
    /**
     * 生成服务审批通知
     */
    public static String generateServicePublicMail(String type, String boeApiName, String userId) {
    	String emailContent = null;
    	if(RELEASE.equals(type)){
    		emailContent = BoeEmailContentConfig.PUBLIC_CONTENT;
    	}else if(SUBSCRIBE.equals(type)){
    		emailContent = BoeEmailContentConfig.SUBSCRIBE_CONTENT;
    	}
    	
        emailContent = emailContent.replace("${apiName}", boeApiName).replace("${userId}", userId);

        String html = "";
        try {
            Template tpl = tplMap.get(ETplType.APPROVAL);
            if (tpl == null) {
                logger.error("contenxt don't init email template of type {}.", ETplType.SERVICE_AUDIT);
                return emailContent;
            }

            Map<String, String> param = Maps.newHashMap();
            param.put("emailContent", emailContent);
            html = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, param);
        } catch (Exception e) {
            logger.error("生成服务审批通知失败", e);
            html = emailContent;
        }
        return html;
    }
}
